/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkGbRtsp.h"
#include "MkUtil/MkUtil.h"
#include "MkUtil/MkLog.h"

CMkGbRtsp::CMkGbRtsp()
    : m_Scale("1.0")
    , m_Version("1.0")
{
    m_Cseq = CMkUtil::GetRandomNumber() % 100;
}

Uint32 CMkGbRtsp::AddContent(const MkString& strContent)
{
    Uint32 nPos = 0;
    MkString strLine;
    Uint32 ErrorCode = CMkUtil::BufferReadLine(strContent, nPos, strLine);
    MkCheckErrorLog(ErrorCode, "real header line failed\n");

    size_t FindPos = strLine.find(" MANSRTSP/");
    if (MkString::npos == FindPos) {
        return InvalidParams;
    }
    m_Method = strLine.substr(0, FindPos);
    m_Version = strLine.substr(FindPos + strlen(" MANSRTSP/"));

    while (NoneError == CMkUtil::BufferReadLine(strContent, nPos, strLine)) {
        MkVectorString VesString;
        ErrorCode = CMkUtil::StringSplit(strLine, ": ", VesString);
        //mast has key value
        if (NoneError != ErrorCode
            || VesString.size() < 2) {
            break;
        }
        if ("PauseTime" == VesString[0]) {
            m_Range = VesString[1];
        } else if ("Scale" == VesString[0]) {
            m_Scale = VesString[1];
        } else if ("Range" == VesString[0]) {
            FindPos = VesString[1].find("npt=");
            int FindPos2 = VesString[1].find("-");
            if (MkString::npos == FindPos
                || MkString::npos == FindPos) {
                ErrorCode = InvalidParams;
                break;
            }
            m_Range = VesString[1].substr(strlen("npt="), FindPos2 - strlen("npt="));
        }
    }
    return NoneError;
}

Uint32 CMkGbRtsp::ToString(MkString& Content)
{
    Content = m_Method + " MANSRTSP/" + m_Version + MkEndLine;
    Content += "CSeq: " + std::to_string(m_Cseq) + MkEndLine;
    if (!m_Scale.empty()) {
        Content += "Scale: " + m_Scale + MkEndLine;
    }
    if (!m_Range.empty()) {
        if ("PLAY" == m_Method) {
            Content += "Range: npt=" + m_Range + "-" + MkEndLine;
        } else if ("PAUSE" == m_Method) {
            Content += "PauseTime: now" + MkString(MkEndLine);
        }
    }
    Content += MkEndLine;
    return NoneError;
}